<template>
  <div class="order-management">
    <h2>订单管理</h2>

    <div class="filter-buttons">
      <el-button
        :type="activeFilter === '全部' ? 'primary' : ''"
        @click="filterOrders('全部')"
      >
      全部
    </el-button>
      <el-button
        :type="activeFilter === '未审核' ? 'primary' : ''"
        @click="filterOrders('未审核')"
      >未审核</el-button>
      <el-button
        :type="activeFilter === '已审核,未支付' ? 'primary' : ''"
        @click="filterOrders('已审核,未支付')"
      >已审核,未支付</el-button>

      <el-button
        :type="activeFilter === '已生效' ? 'primary' : ''"
        @click="filterOrders('已生效')"
      >已生效</el-button>
    </div>

    <div v-loading="loading" class="order-container">
      <div v-if="filteredOrders.length === 0" class="no-orders">
        <el-empty description="暂无相关订单" />
      </div>

      <div v-for="order in filteredOrders" :key="order.order_id" class="order-card">
        <div class="order-header">
          <span class="order-time">{{ formatDate(order.order_time) }}</span>
          <span class="order-id">订单号: {{ order.order_id }}</span>
          <el-tag :type="statusTagType(order.order_status)" class="status-tag">
            {{ order.order_status }}
          </el-tag>
        </div>

        <div class="order-body">
          <div class="product-info">
            <div class="product-image">
              <!-- 实际项目中这里应该是商品图片 -->
              <div class="image-placeholder">
                <el-icon><Picture /></el-icon>
              </div>
            </div>
            <div class="product-details">
              <div class="product-name">{{ order.order_product.name }}</div>
              <div class="product-price">￥{{ order.order_price }}</div>
            </div>
          </div>

          <div class="order-actions">
            <el-button
              size="small"
              @click="viewOrderDetail(order)"
              >查看详情</el-button>
          </div>
        </div>

        <div class="order-footer">
          <div class="total-price">实付款: <span>￥{{ order.order_price }}</span></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox, ElIcon } from 'element-plus';
import { Picture } from '@element-plus/icons-vue';
import axios from 'axios';
import { useRouter } from 'vue-router'; // 导入 useRouter

const router = useRouter(); // 获取路由实例
const orders = ref([]);
const loading = ref(false);
const activeFilter = ref('全部');

// 获取当前用户ID
const userId = localStorage.getItem('user_id') || '';

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleDateString() + ' ' + date.toLocaleTimeString().slice(0,5);
};

// 状态标签类型
const statusTagType = (status) => {
  switch(status) {
    case '待支付': return 'danger';
    case '已支付': return 'warning';
    case '生效中': return 'primary';
    case '已生效': return 'success';
    default: return 'info';
  }
};

// 过滤订单
const filteredOrders = computed(() => {
  if (activeFilter.value === '全部') return orders.value;
  return orders.value.filter(order => order.order_status === activeFilter.value);
});

// 获取用户订单
const fetchOrders = async () => {
  if (!userId) {
    ElMessage.error('用户信息获取失败');
    return;
  }

  try {
    loading.value = true;
    const response = await axios.get('http://127.0.0.1:8000/orders/order_query/', {
      params: {
        user_id: userId  // 使用user_id作为参数
      }
    });

    if (response.data.status === 200) {
      orders.value = response.data.data;
    } else {
      ElMessage.error('获取订单失败: ' + response.data.msg);
    }
  } catch (error) {
    console.error('获取订单失败:', error);
    ElMessage.error('获取订单失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 支付订单
const payOrder = (order) => {
  ElMessageBox.confirm(
    `确定要支付订单 ${order.order_id} 吗？金额: ￥${order.order_price}`,
    '确认支付',
    {
      confirmButtonText: '确认支付',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await axios.post('http://127.0.0.1:8000/orders/order_pay/', {
        user_id: userId,  // 使用user_id作为参数
        order_id: order.order_id  // 参数名改为order_id
      });

      if (response.data.status === 200) {
        ElMessage.success('支付成功');
        // 刷新订单列表
        fetchOrders();
      } else {
        ElMessage.error('支付失败: ' + response.data.msg);
      }
    } catch (error) {
      console.error('支付失败:', error);
      ElMessage.error('支付失败，请稍后重试');
    }
  }).catch(() => {
    // 用户取消
  });
};

// 查看订单详情
const viewOrderDetail = (order) => {
  // 使用命名路由并传递订单ID
  router.push({
    name: 'order-detail',
    params: { id: order.id }
  });
};

// 过滤订单
const filterOrders = (status) => {
  activeFilter.value = status;
};

onMounted(() => {
  fetchOrders();
});
</script>

<style scoped>
.order-management {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.filter-buttons {
  margin-bottom: 20px;
}

.filter-buttons .el-button {
  margin-right: 10px;
}

.order-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.order-card {
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  background-color: #fff;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.03);
  transition: all 0.3s;
}

.order-card:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
}

.order-header {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  background-color: #fafafa;
  border-bottom: 1px solid #eee;
  font-size: 13px;
  color: #666;
}

.order-time {
  margin-right: 20px;
}

.order-id {
  flex: 1;
}

.status-tag {
  margin-left: 10px;
}

.order-body {
  display: flex;
  padding: 16px;
}

.product-info {
  display: flex;
  flex: 1;
}

.product-image {
  width: 80px;
  height: 80px;
  margin-right: 16px;
}

.image-placeholder {
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #c0c4cc;
  border-radius: 4px;
}

.product-details {
  flex: 1;
}

.product-name {
  font-size: 14px;
  color: #333;
  margin-bottom: 8px;
  line-height: 1.4;
}

.product-price {
  font-size: 16px;
  color: #f56c6c;
  font-weight: bold;
}

.order-actions {
  display: flex;
  align-items: center;
  padding-left: 20px;
}

.order-footer {
  display: flex;
  justify-content: flex-end;
  padding: 10px 16px;
  border-top: 1px solid #eee;
  background-color: #fff;
}

.total-price {
  font-size: 14px;
  color: #666;
}

.total-price span {
  font-size: 18px;
  color: #f56c6c;
  font-weight: bold;
  margin-left: 5px;
}

.no-orders {
  text-align: center;
  padding: 40px 0;
  color: #999;
}
</style>